package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.company.bean.EnumManage;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 部门
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-10 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/department")
public class DepartmentController extends BaseController {

    private static final long serialVersionUID = -8888792327150504194L;

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private DutyService dutyService;

    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user, Model model,
                         @RequestParam(required = false) String departmentId) {

        model.addAttribute("departmentId", departmentId);
        return "/main/company/department_input";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {

        model.addAttribute("keyId", keyId);
        return "/main/company/department_input";
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       @RequestParam(required = false) String parentId,
                       Department department) {
        // 必填校验
        if (StringUtils.isBlank(department.getName())) {
            return resultService.fail("部门名称不能为空");
        }
        // 上级部门
        if (StringUtils.isNotBlank(parentId)) {
            Department parent = departmentService.get(parentId);
            if (parent != null) {
                department.setParent(parent);
            }
        }

        if (StringUtils.isBlank(keyId)) {// 保存
            return ajaxJson(departmentService.createEntity(user, department));
        } else {// 修改
            return ajaxJson(departmentService.updateEntity(user, keyId, department));
        }
    }

    /**
     * 初始化表单
     */
    @RequestMapping(value = "init", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object init(@CurrentUser User user,
                       @RequestParam(required = false) String departmentId) {
        Department department = new Department();
        if (StringUtils.isNotBlank(departmentId)) {
            Department parent = departmentService.get(departmentId);
            if (parent != null) {
                department.setParent(parent);
            }
        }

        Map<String, Object> dataMap = departmentService.getDetailMap(department);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 获取详情
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object read(@CurrentUser User user,
                       @PathVariable String keyId) {
        Department department = departmentService.get(keyId);
        if (department == null){
            department = new Department();
        }

        Map<String, Object> dataMap = departmentService.getDetailMap(department);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * tree
     */
    @RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Map<String, Object>> tree(@CurrentUser User user,
                                          @RequestParam(required = false) String id) {
        Company company = user.getCompany();

        List<Department> departmentList = null;
        ArrayList<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

        if (StringUtils.isBlank(id)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", "0");
            map.put("name", company.getName());
            map.put("isParent", departmentService.isParentDepartment(null));
            mapList.add(map);
            return mapList;
        } else if (StringUtils.equals("0", id)) {
            departmentList = departmentService.getRootDepartments(company);
        } else {
            Department department = departmentService.get(id);
            if (department != null) {
                departmentList = departmentService.getDepartments(company, department);
            }
        }
        if (departmentList == null) {
            departmentList = new ArrayList<Department>();
        }

        for (Department department : departmentList) {
            Map<String, Object> map = departmentService.getTreeMap(department);

            mapList.add(map);
        }

        return mapList;
    }

    /**
     * 选择用户所在部门(多个)
     */
    @RequestMapping(value = "dialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialoguserdept(@CurrentUser User user,@RequestParam() String multi, String deptIds, Model model) {
        model.addAttribute("multi", multi);
        if (StringUtils.isNotEmpty(deptIds)){
            String arr[] = deptIds.split(",");
            model.addAttribute("deptIds", arr);
        }

        return "/main/company/department_dialog";
    }

    /**
     * 删除职责信息
     * @return
     */
    @RequestMapping(value = "lead", method = RequestMethod.POST)
    public Object lead(@CurrentUser User user ,String keyId, String rowId){
        if(StringUtils.isEmpty(keyId)){
            return resultService.fail("请选择部门!");
        }
        if(StringUtils.isEmpty(rowId)){
            return resultService.fail("请选择职责!");
        }
        Set<Post> postSet = new HashSet();
        Set<Duty> dutySet =new HashSet<Duty>();

        Department department =departmentService.get(keyId);
        Duty duty1=dutyService.get(rowId);
        //将之前的部门负责人变成组员
        Duty duty = dutyService.getPrincipalDuty(department);
        if(duty1.getDutyState()== EnumManage.DutyState.Principal){
            duty.setDutyState(EnumManage.DutyState.Default);
            dutyService.update(duty);
        }else{
            //将组员变成部门负责人
            if(duty!=null){
                duty.setDutyState(EnumManage.DutyState.Default);
                dutyService.update(duty);
            }
            duty1.setDutyState(EnumManage.DutyState.Principal);
            dutyService.update(duty1);
        }
        return ajaxJson(resultService.success());
    }

    /**
     * 操作
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Object delete(@CurrentUser User user, String keyId) {
        if(StringUtils.isEmpty(keyId)){
            return resultService.fail("请选择部门!");
        }
        Result result = departmentService.methodEntity(user, "Delete", keyId);
        return ajaxJson(result);
    }
}
